<?php

namespace App\Jobs;

use App\Models\DownloadJob;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
use Illuminate\Support\Facades\File;
use Illuminate\Support\Facades\Storage;
use PhpOffice\PhpSpreadsheet\IOFactory;
use PhpOffice\PhpSpreadsheet\Exception;
use PhpOffice\PhpSpreadsheet\Writer\Exception as WriterException;

class MergeExcel implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;

    protected $downloadId;
    protected $dirStorage;
    protected $storagePath;

    /**
     * Create a new job instance.
     *
     * @return void
     */
    public function __construct($downloadId, $dirStorage)
    {
        $this->downloadId  = $downloadId;
        $this->dirStorage  = $dirStorage;
        $this->storagePath = storage_path('app/public/') . $dirStorage; //在队列里面这里有些不同，必须使用绝对路径
    }

    /**
     * Execute the job.
     *
     * @throws Exception
     * @throws WriterException
     * @author: lxk
     * @date: 2024-12-09 14:08
     */
    public function handle()
    {
        $files = File::allFiles($this->storagePath);
        asort($files, SORT_STRING | SORT_FLAG_CASE | SORT_NATURAL); // 对值排序
        $files      = array_values($files);
        $firstExcel = $this->storagePath . '/' . $files[0]->getFilename();
        $baseExcel  = IOFactory::load($firstExcel);
        unset($files[0]);
        foreach ($files as $file) {
            $loadExcel = IOFactory::load($this->storagePath . '/' . $file->getFilename());
            $baseExcel->addExternalSheet($loadExcel->getActiveSheet());
        }
        $endSlashPos    = strrpos($this->storagePath, '/');
        $mergedFileName = substr($this->storagePath, $endSlashPos) . ".xlsx"; // 中铁二十局集团有限公司（XCZQ-8标）_施工标段综合文件_案卷序号【1~50】卷内目录_151022.xlsx
        $newDirStorage  = substr($this->storagePath, 0, $endSlashPos);
        $mergedFile     = $newDirStorage . $mergedFileName;
        $writer         = IOFactory::createWriter($baseExcel, 'Xlsx');
        $writer->save($mergedFile);

        $needDelDir = str_replace('storage', '/public', $this->dirStorage);
        Storage::deleteDirectory($needDelDir); //用完删除
        $downloadDir = 'storage/excels/'.$mergedFileName;
        DownloadJob::query()->where('id', $this->downloadId)->update(['status' => 3, 'download_url' => config('site.domain') . $downloadDir]);
    }

    /**
     * 任务失败
     *
     * @param \Throwable $exception
     * @author: lxk
     * @date: 2024-12-09 15:27
     */
    public function fail(\Throwable $exception)
    {
        info('---------出错了---------');
        info($exception->getMessage());
        DownloadJob::query()->where('id', $this->downloadId)->update(['status' => 4]);
    }

}
